package net.rain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.rain.common.CurrentUser;
import net.rain.common.Result;
import net.rain.entity.dto.UserDTO;
import net.rain.entity.dto.LoginDTO;
import net.rain.utils.exception.UserLoginException;
import net.rain.entity.pojo.user.RainyUser;
import net.rain.mapper.RainyUserMapper;
import net.rain.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static net.rain.utils.RainConstants.LOGIN_USER_KEY;
import static net.rain.utils.RainConstants.LOGIN_USER_TTL;

/**
 * @author Rainy-Heights
 * @version 1.0
 * @Date 2023/4/24 16:42
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<RainyUserMapper, RainyUser> implements UserService {
    @Resource
    RainyUserMapper userMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(LoginDTO loginDTO) {

        QueryChainWrapper<RainyUser> chainWrapper = query().eq("id", loginDTO.getId())
                .eq("username", loginDTO.getUsername())
                .eq("password", loginDTO.getPassword());
        List<RainyUser> users = chainWrapper.list();
        //用户不为空，返回查询到的用户。

        //判空用这个来解决
        if (users.isEmpty()){
            //抛出登录异常信息
            throw new UserLoginException("输入信息有误或不存在该用户");
        }
        //添加用户信息
        String token= UUID.randomUUID().toString(true);
        UserDTO userDTO= BeanUtil.copyProperties(users.get(0), UserDTO.class);
        Map<String,Object> userMap=BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        String tokenKey=LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        CurrentUser.saveUser(userDTO);
        return Result.success(token);
    }

    @Override
    public RainyUser getUser(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public RainyUser sign(RainyUser rainyUser) {
        LambdaQueryWrapper<RainyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RainyUser::getId,rainyUser.getId());
        List<RainyUser> historyUser = userMapper.selectList(queryWrapper);

        if (!historyUser.isEmpty()){
            throw new UserLoginException("该用户已存在，无需继续注册");
        }else {
            userMapper.insert(rainyUser);
            System.out.println(rainyUser);
        }
        return userMapper.selectById(rainyUser.getId());
    }
}
